[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isIPageInfoForEntity } from '@growi/core';
  4. import type {
  5. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  6. } from '@growi/core';
  7. import {
  8. isClient, pagePathUtils, pathUtils,
  9. } from '@growi/core/dist/utils';
  10. import ExtensibleCustomError from 'extensible-custom-error';
  11. import type {
  12. GetServerSideProps, GetServerSidePropsContext,
  13. } from 'next';
  14. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  15. import dynamic from 'next/dynamic';
  16. import Head from 'next/head';
  17. import { useRouter } from 'next/router';
  18. import superjson from 'superjson';
  19. import { useEditorModeClassName } from '~/client/services/layout';
  20. import { PageView } from '~/components/Page/PageView';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  22. import type { CrowiRequest } from '~/interfaces/crowi-request';
  23. import type { EditorConfig } from '~/interfaces/editor-settings';
  24. import type { IPageGrantData } from '~/interfaces/page';
  25. import type { RendererConfig } from '~/interfaces/services/renderer';
  26. import type { PageModel, PageDocument } from '~/server/models/page';
  27. import type { PageRedirectModel } from '~/server/models/page-redirect';
  28. import {
  29. useCurrentUser,
  30. useIsForbidden, useIsSharedUser,
  31. useIsEnabledStaleNotification, useIsIdenticalPath,
  32. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  33. useDefaultIndentSize, useIsIndentSizeForced,
  34. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  35. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  36. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  37. useEditorConfig, useIsAllReplyShown, useIsUploadAllFileAllowed, useIsUploadEnabled, useIsContainerFluid, useIsNotCreatable,
  38. } from '~/stores/context';
  39. import { useEditingMarkdown } from '~/stores/editor';
  40. import {
  41. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  42. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  43. } from '~/stores/page';
  44. import { useRedirectFrom } from '~/stores/page-redirect';
  45. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  46. import { useSelectedGrant } from '~/stores/ui';
  47. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  48. import loggerFactory from '~/utils/logger';
  49. import { BasicLayout } from '../components/Layout/BasicLayout';
  50. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  51. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  52. import type { NextPageWithLayout } from './_app.page';
  53. import type { CommonProps } from './utils/commons';
  54. import {
  55. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  56. } from './utils/commons';
  57. declare global {
  58. // eslint-disable-next-line vars-on-top, no-var
  59. var globalEmitter: EventEmitter;
  60. }
  61. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  62. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  63. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  64. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  65. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  66. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  67. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  68. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  69. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  70. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  71. const logger = loggerFactory('growi:pages:all');
  72. const {
  73. isPermalink: _isPermalink, isCreatablePage,
  74. } = pagePathUtils;
  75. const { removeHeadingSlash } = pathUtils;
  76. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  77. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  78. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  79. {
  80. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  81. return v?.data != null
  82. && v?.data.toObject != null
  83. && v?.meta != null
  84. && isIPageInfoForEntity(v.meta);
  85. },
  86. serialize: (v) => {
  87. return {
  88. data: superjson.stringify(v.data.toObject()),
  89. meta: superjson.stringify(v.meta),
  90. };
  91. },
  92. deserialize: (v) => {
  93. return {
  94. data: superjson.parse(v.data),
  95. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  96. };
  97. },
  98. },
  99. 'IPageToShowRevisionWithMetaTransformer',
  100. );
  101. // GrowiContextualSubNavigation for NOT shared page
  102. type GrowiContextualSubNavigationProps = {
  103. isLinkSharingDisabled: boolean,
  104. }
  105. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  106. const { isLinkSharingDisabled } = props;
  107. const { data: currentPage } = useSWRxCurrentPage();
  108. return (
  109. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  110. );
  111. };
  112. type Props = CommonProps & {
  113. pageWithMeta: IPageToShowRevisionWithMeta | null,
  114. // pageUser?: any,
  115. redirectFrom?: string;
  116. // shareLinkId?: string;
  117. isLatestRevision?: boolean,
  118. isIdenticalPathPage?: boolean,
  119. isForbidden: boolean,
  120. isNotFound: boolean,
  121. isNotCreatable: boolean,
  122. // isAbleToDeleteCompletely: boolean,
  123. templateTagData?: string[],
  124. templateBodyData?: string,
  125. isSearchServiceConfigured: boolean,
  126. isSearchServiceReachable: boolean,
  127. isSearchScopeChildrenAsDefault: boolean,
  128. isEnabledMarp: boolean,
  129. isSlackConfigured: boolean,
  130. // isMailerSetup: boolean,
  131. isAclEnabled: boolean,
  132. // hasSlackConfig: boolean,
  133. drawioUri: string | null,
  134. noCdn: string,
  135. // highlightJsStyle: string,
  136. isAllReplyShown: boolean,
  137. isContainerFluid: boolean,
  138. editorConfig: EditorConfig,
  139. isEnabledStaleNotification: boolean,
  140. isEnabledAttachTitleHeader: boolean,
  141. // isEnabledLinebreaks: boolean,
  142. // isEnabledLinebreaksInComments: boolean,
  143. adminPreferredIndentSize: number,
  144. isIndentSizeForced: boolean,
  145. disableLinkSharing: boolean,
  146. skipSSR: boolean,
  147. ssrMaxRevisionBodyLength: number,
  148. grantData?: IPageGrantData,
  149. rendererConfig: RendererConfig,
  150. };
  151. const Page: NextPageWithLayout<Props> = (props: Props) => {
  152. // register global EventEmitter
  153. if (isClient() && window.globalEmitter == null) {
  154. window.globalEmitter = new EventEmitter();
  155. }
  156. const router = useRouter();
  157. useCurrentUser(props.currentUser ?? null);
  158. // commons
  159. useEditorConfig(props.editorConfig);
  160. useCsrfToken(props.csrfToken);
  161. useGrowiCloudUri(props.growiCloudUri);
  162. // page
  163. useIsContainerFluid(props.isContainerFluid);
  164. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  165. useIsForbidden(props.isForbidden);
  166. useIsNotCreatable(props.isNotCreatable);
  167. useRedirectFrom(props.redirectFrom ?? null);
  168. useIsSharedUser(false); // this page cann't be routed for '/share'
  169. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  170. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  171. useIsSearchPage(false);
  172. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  173. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  174. useIsSearchServiceReachable(props.isSearchServiceReachable);
  175. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  176. useIsSlackConfigured(props.isSlackConfigured);
  177. // useIsMailerSetup(props.isMailerSetup);
  178. useIsAclEnabled(props.isAclEnabled);
  179. // useHasSlackConfig(props.hasSlackConfig);
  180. // useNoCdn(props.noCdn);
  181. useDefaultIndentSize(props.adminPreferredIndentSize);
  182. useIsIndentSizeForced(props.isIndentSizeForced);
  183. useDisableLinkSharing(props.disableLinkSharing);
  184. useRendererConfig(props.rendererConfig);
  185. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  186. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  187. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  188. useIsAllReplyShown(props.isAllReplyShown);
  189. useIsUploadAllFileAllowed(props.editorConfig.upload.isUploadAllFileAllowed);
  190. useIsUploadEnabled(props.editorConfig.upload.isUploadEnabled);
  191. const { pageWithMeta } = props;
  192. const pageId = pageWithMeta?.data._id;
  193. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  194. const revisionBody = pageWithMeta?.data.revision?.body;
  195. useCurrentPathname(props.currentPathname);
  196. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  197. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  198. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  199. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  200. const { mutate: mutateIsNotFound } = useIsNotFound();
  201. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  202. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  203. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  204. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  205. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  206. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  207. useSetupGlobalSocket();
  208. useSetupGlobalSocketForPage(pageId);
  209. // Store initial data (When revisionBody is not SSR)
  210. useEffect(() => {
  211. if (!props.skipSSR) {
  212. return;
  213. }
  214. if (currentPageId != null && !props.isNotFound) {
  215. const mutatePageData = async() => {
  216. const pageData = await mutateCurrentPage();
  217. mutateEditingMarkdown(pageData?.revision.body);
  218. };
  219. // If skipSSR is true, use the API to retrieve page data.
  220. // Because pageWIthMeta does not contain revision.body
  221. mutatePageData();
  222. }
  223. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  224. // sync grant data
  225. useEffect(() => {
  226. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  227. mutateSelectedGrant(grantDataToApply);
  228. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  229. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  230. useEffect(() => {
  231. const decodedURI = decodeURI(window.location.pathname);
  232. if (isClient() && decodedURI !== props.currentPathname) {
  233. const { search, hash } = window.location;
  234. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  235. }
  236. }, [props.currentPathname, router]);
  237. // initialize mutateEditingMarkdown only once per page
  238. // need to include useCurrentPathname not useCurrentPagePath
  239. useEffect(() => {
  240. if (props.currentPathname != null) {
  241. mutateEditingMarkdown(revisionBody);
  242. }
  243. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  244. useEffect(() => {
  245. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  246. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  247. useEffect(() => {
  248. mutateCurrentPageId(pageId ?? null);
  249. }, [mutateCurrentPageId, pageId]);
  250. useEffect(() => {
  251. mutateIsNotFound(props.isNotFound);
  252. }, [mutateIsNotFound, props.isNotFound]);
  253. useEffect(() => {
  254. mutateIsLatestRevision(props.isLatestRevision);
  255. }, [mutateIsLatestRevision, props.isLatestRevision]);
  256. useEffect(() => {
  257. mutateTemplateTagData(props.templateTagData);
  258. }, [props.templateTagData, mutateTemplateTagData]);
  259. useEffect(() => {
  260. mutateTemplateBodyData(props.templateBodyData);
  261. }, [props.templateBodyData, mutateTemplateBodyData]);
  262. const title = generateCustomTitleForPage(props, pagePath);
  263. return (
  264. <>
  265. <Head>
  266. <title>{title}</title>
  267. </Head>
  268. <div className="dynamic-layout-root justify-content-between">
  269. <nav className="sticky-top">
  270. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  271. </nav>
  272. <DisplaySwitcher
  273. pageView={(
  274. <PageView
  275. pagePath={pagePath}
  276. initialPage={pageWithMeta?.data}
  277. rendererConfig={props.rendererConfig}
  278. />
  279. )}
  280. />
  281. <PageStatusAlert />
  282. </div>
  283. </>
  284. );
  285. };
  286. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  287. const editorModeClassName = useEditorModeClassName();
  288. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  289. };
  290. type LayoutProps = Props & {
  291. children?: ReactNode
  292. }
  293. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  294. // init sidebar config with UserUISettings and sidebarConfig
  295. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  296. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  297. };
  298. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  299. return (
  300. <>
  301. <GrowiPluginsActivator />
  302. <DrawioViewerScript />
  303. <Layout {...page.props}>
  304. {page}
  305. </Layout>
  306. <UnsavedAlertDialog />
  307. <DescendantsPageListModal />
  308. <DrawioModal />
  309. <HandsontableModal />
  310. <QuestionnaireModalManager />
  311. <TemplateModal />
  312. <LinkEditModal />
  313. <TagEditModal />
  314. </>
  315. );
  316. };
  317. function getPageIdFromPathname(currentPathname: string): string | null {
  318. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  319. }
  320. class MultiplePagesHitsError extends ExtensibleCustomError {
  321. pagePath: string;
  322. constructor(pagePath: string) {
  323. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  324. this.pagePath = pagePath;
  325. }
  326. }
  327. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  328. const { model: mongooseModel } = await import('mongoose');
  329. const req: CrowiRequest = context.req as CrowiRequest;
  330. const { crowi } = req;
  331. const { revisionId } = req.query;
  332. const Page = crowi.model('Page') as PageModel;
  333. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  334. const { pageService, configManager } = crowi;
  335. let currentPathname = props.currentPathname;
  336. const pageId = getPageIdFromPathname(currentPathname);
  337. const isPermalink = _isPermalink(currentPathname);
  338. const { user } = req;
  339. if (!isPermalink) {
  340. // check redirects
  341. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  342. if (chains != null) {
  343. // overwrite currentPathname
  344. currentPathname = chains.end.toPath;
  345. props.currentPathname = currentPathname;
  346. // set redirectFrom
  347. props.redirectFrom = chains.start.fromPath;
  348. }
  349. // check whether the specified page path hits to multiple pages
  350. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  351. if (count > 1) {
  352. throw new MultiplePagesHitsError(currentPathname);
  353. }
  354. }
  355. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  356. const page = pageWithMeta?.data as unknown as PageDocument;
  357. // add user to seen users
  358. if (page != null && user != null) {
  359. await page.seen(user);
  360. }
  361. // populate & check if the revision is latest
  362. if (page != null) {
  363. page.initLatestRevisionField(revisionId);
  364. props.isLatestRevision = page.isLatestRevision();
  365. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  366. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  367. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  368. }
  369. if (page == null && user != null) {
  370. const templateData = await Page.findTemplate(props.currentPathname);
  371. if (templateData != null) {
  372. props.templateTagData = templateData.templateTags as string[];
  373. props.templateBodyData = templateData.templateBody as string;
  374. }
  375. // apply parent page grant, without groups that user isn't related to
  376. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  377. if (ancestor != null) {
  378. const userRelatedGrantedGroups = await pageService.getUserRelatedGrantedGroups(ancestor, user);
  379. props.grantData = {
  380. grant: ancestor.grant,
  381. grantedGroups: userRelatedGrantedGroups.map((group) => {
  382. return {
  383. id: group.item._id,
  384. name: group.item.name,
  385. type: group.type,
  386. };
  387. }),
  388. };
  389. }
  390. }
  391. props.pageWithMeta = pageWithMeta;
  392. }
  393. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  394. const req: CrowiRequest = context.req as CrowiRequest;
  395. const { crowi } = req;
  396. const Page = crowi.model('Page') as PageModel;
  397. const { currentPathname } = props;
  398. const pageId = getPageIdFromPathname(currentPathname);
  399. const isPermalink = _isPermalink(currentPathname);
  400. const page = props.pageWithMeta?.data;
  401. if (props.isIdenticalPathPage) {
  402. props.isNotCreatable = true;
  403. }
  404. else if (page == null) {
  405. props.isNotFound = true;
  406. props.isNotCreatable = !isCreatablePage(currentPathname);
  407. // check the page is forbidden or just does not exist.
  408. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  409. props.isForbidden = count > 0;
  410. }
  411. else {
  412. props.isNotFound = page.isEmpty;
  413. props.isNotCreatable = false;
  414. props.isForbidden = false;
  415. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  416. if (isPermalink && page.isEmpty) {
  417. props.currentPathname = page.path;
  418. }
  419. // /path/to/page ==> /62a88db47fed8b2d94f30000
  420. if (!isPermalink && !page.isEmpty) {
  421. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  422. if (!isToppage) {
  423. props.currentPathname = `/${page._id}`;
  424. }
  425. }
  426. }
  427. }
  428. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  429. // const req: CrowiRequest = context.req as CrowiRequest;
  430. // const { crowi } = req;
  431. // const UserModel = crowi.model('User');
  432. // if (isUserPage(props.currentPagePath)) {
  433. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  434. // if (user != null) {
  435. // props.pageUser = JSON.stringify(user.toObject());
  436. // }
  437. // }
  438. // }
  439. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  440. const req: CrowiRequest = context.req as CrowiRequest;
  441. const { crowi } = req;
  442. const {
  443. searchService, configManager, aclService,
  444. } = crowi;
  445. props.isSearchServiceConfigured = searchService.isConfigured;
  446. props.isSearchServiceReachable = searchService.isReachable;
  447. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  448. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  449. // props.isMailerSetup = mailService.isMailerSetup;
  450. props.isAclEnabled = aclService.isAclEnabled();
  451. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  452. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  453. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  454. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  455. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  456. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  457. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  458. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  459. props.editorConfig = {
  460. upload: {
  461. isUploadAllFileAllowed: crowi.fileUploadService.getFileUploadEnabled(),
  462. isUploadEnabled: crowi.fileUploadService.getIsUploadable(),
  463. },
  464. };
  465. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  466. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  467. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  468. props.rendererConfig = {
  469. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  470. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  471. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  472. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  473. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  474. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  475. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  476. // XSS Options
  477. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  478. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  479. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  480. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  481. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  482. };
  483. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  484. }
  485. /**
  486. * for Server Side Translations
  487. * @param context
  488. * @param props
  489. * @param namespacesRequired
  490. */
  491. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  492. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  493. props._nextI18Next = nextI18NextConfig._nextI18Next;
  494. }
  495. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  496. const req = context.req as CrowiRequest;
  497. const { user } = req;
  498. const result = await getServerSideCommonProps(context);
  499. // check for presence
  500. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  501. if (!('props' in result)) {
  502. throw new Error('invalid getSSP result');
  503. }
  504. const props: Props = result.props as Props;
  505. if (props.redirectDestination != null) {
  506. return {
  507. redirect: {
  508. permanent: false,
  509. destination: props.redirectDestination,
  510. },
  511. };
  512. }
  513. if (user != null) {
  514. props.currentUser = user.toObject();
  515. }
  516. try {
  517. await injectPageData(context, props);
  518. }
  519. catch (err) {
  520. if (err instanceof MultiplePagesHitsError) {
  521. props.isIdenticalPathPage = true;
  522. }
  523. else {
  524. throw err;
  525. }
  526. }
  527. await injectRoutingInformation(context, props);
  528. injectServerConfigurations(context, props);
  529. await injectNextI18NextConfigurations(context, props, ['translation']);
  530. return {
  531. props,
  532. };
  533. };
  534. export default Page;